/*
 * weibo.js 实现weibo的AJAX请求的提交
 * color()
 * ajaxpublish(content, forwardid)
 * ajaxcomment(weiboid, action, commentid)
 * forward(forwardid)
 * delete_weibo(weiboid)
 * query_comment(weiboid)
 * add_comment(weiboid)
 * delete_comment(weiboid, commentid)
 * reply_comment(weiboid, nick)
 * $(function()
 * version: 1.0
 * date: 2011.09.21
 */

//颜色渐变
var gb = 150;
function color(){ 
	if(gb<=255){
		var rgbcolor = "rgb(255, "+gb+", "+gb+")";
		$("textarea.weibo").delay("500").css("background-color", rgbcolor);
		gb++;
		setTimeout("color()", 5);
	} else {
		gb = 150;
	}
}

//AJAX发布微博
function ajaxpublish(content, forwardid, picture){//发表新微博时forwardid==-1，转发时forwardid为引用的微博的id
	var ctx = $("#ctx").attr("title");
	$.ajax({
		url: ctx+"/publishWeibo",
		type: "post",
		async: true,	//请求是否异步，默认为异步
		data: {"weibo.content":content, "weibo.forwardid":forwardid, "weibo.picture":picture},
//		dataType: "json",
	    beforeSend: function() {
	        //请求前的处理
			if(forwardid == -1){
				if($("textarea.weibo").val() == ""){
					color();
					$("textarea.weibo").focus();
					return false;
				} else {
					$("textarea.weibo").addClass("loading");
				}
			}
		},
		success: function(data){
			if(forwardid == -1){
				$("textarea.weibo").val("");
				$("textarea.weibo").removeClass("loading");
				$("textarea.weibo").addClass("success");
				setTimeout(function(){
					$("textarea.weibo").removeClass("success");
				}, 1000);
				$("textarea.weibo").focus();//todo: 应在 removeClass("success") 后 focus
			}else{
				tb_remove();
			}
			if(picture != -1){
				$("#picture_layer").hide();
				$("#picture_upload").hide();
				$("p.rawname").html("");
	        	$("img.upload").attr("src", "");
				$("img.upload").attr("id", "-1");
			}
			var jsondata =jQuery.parseJSON(data);
//			$("ul#weibolist").empty();
		    $("<div>").load(ctx+"/weibo.jsp #tempul", jsondata, function(){
//		    	 关于在ajax中新增的class='thickbox' 点击显示不出弹出层的原因
//		    	js的文档加载时在页面加载完成后生效的，新加入的属性不起作用，可以通过
//		    	tb_init('a.thickbox, area.thickbox, input.thickbox');来重新加载thickbox
		    	$.getScript(ctx+"/js/init.js");
		    	$("ul#weibolist").prepend($(this).find("#tempul").html());
		    });
		},
		complete: function() {
	        // 请求完成的处理
	    },
	    error: function() {
	        // 请求出错处理
	    	alert("error...");
	    }
	});
}

//AJAX查询|发布|删除评论
function ajaxcomment(weiboid, action, commentid){
	var ctx = $("#ctx").attr("title");
	var content = $("#comment_content_"+weiboid).val();
	$.ajax({
		url: ctx+"/"+action+"Comment",
		type: "post",
		data: {"comment.weiboid":weiboid, "action":action, "comment.id":commentid, "comment.content":content},
//		dataType: "json",
		error: function(){
			alert("error...");
		},
		success: function(data){
			var jsondata =jQuery.parseJSON(data);
			if(action == "publish"){
				$("#comment_content_"+weiboid).val("");
				$("<div>").load(ctx+"/comment.jsp #tempul", jsondata, function(){
					$("#commentlist_"+weiboid).prepend($(this).find("#tempul").html());
				});
			}
			if(action == "list"){
				$.each(jsondata, function(i, item){
					$("<div>").load(ctx+"/comment.jsp #tempul", item, function(){
						$("#commentlist_"+weiboid).append($(this).find("#tempul").html());
					});
				});
			}
			if(action == "delete"){
				$("#comment_"+commentid).fadeOut("slow");
			}
		}
	});
}

//转发微博
function forward(forwardid) {
	var ctx = $("#ctx").attr("title");
	var content = $("#popforward_content").val();
	ajaxpublish(content, forwardid, -1);
}

//删除微博
function delete_weibo(weiboid){
	var ctx = $("#ctx").attr("title");
//	alert(ctx);
	if(confirm("确认要删除这条微博吗？")){
		$.ajax({
			url: ctx+"/deleteWeibo",
			type: "post",
			data: {"weibo.id":weiboid},
			error: function(){
				alert("error...");
			},
			success: function(data){
				$("#weibo_"+weiboid).fadeOut("slow");
			}
		});
	}else {
		return;
	}
}

//查询评论
function query_comment(weiboid){
	if($("#"+weiboid).css("display") == "none"){
		$("#"+weiboid).show();
		ajaxcomment(weiboid, "list", -1);
	}else{
		$("#commentlist_"+weiboid).empty();
		$("#"+weiboid).hide();
	}
}

//发布评论
function add_comment(weiboid){
	ajaxcomment(weiboid, "publish", -1);
}

//删除评论
function delete_comment(weiboid, commentid){
	if(confirm("确定要删除该回复吗？")){
		ajaxcomment(weiboid, "delete", commentid);
	}else {
		return;
	}
}

//回复评论
function reply_comment(weiboid, nick){
	$("#comment_content_"+weiboid).val('回复@'+nick+':');
}

//unused
function loadjscssfile(filename, filetype){
	if (filetype=="js"){
		var fileref=document.createElement('script');
		fileref.setAttribute("type","text/javascript");
		fileref.setAttribute("src", filename);
	}
	else if (filetype=="css"){
	var fileref=document.createElement("link");
		fileref.setAttribute("rel", "stylesheet");
		fileref.setAttribute("type", "text/css");
		fileref.setAttribute("href", filename);
	}
	if (typeof fileref!="undefined"){
		document.getElementsByTagName("head")[0].appendChild(fileref);
	}
}

//unused
function removejscssfile(filename, filetype){
	var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none";
	var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none";
	var allsuspects=document.getElementsByTagName(targetelement);
	for (var i=allsuspects.length; i>=0; i--){
		if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(filename)!=-1){
			allsuspects[i].parentNode.removeChild(allsuspects[i]);
		}
	}
}

//AJAX关注
function ajaxfollow(followid, type){
	var ctx = $("#ctx").attr("title");
	$.ajax({
		url: ctx+"/"+type+"Follow",
		type: "post",
		data: {"follow.followid":followid},
		error: function(){
			alert("error...");
		},
		success: function(data){
			var jsondata = jQuery.parseJSON(data);
			if(jsondata.result == "success"){
				if (type=="add") {
					$("#follow_"+followid).html("取消关注");
					$("#follow_"+followid).attr("href",'javascript:cancel_follow("'+followid+'");');
				} else {
					$("#follow_"+followid).html("加关注");
					$("#follow_"+followid).attr("href",'javascript:add_follow("'+followid+'");');
				}
			}
		}
	});
}

function add_follow(followid){
	ajaxfollow(followid, "add");
}

function cancel_follow(followid){
	ajaxfollow(followid, "cancel");
}

function search_user(search){
	var ctx = $("#ctx").attr("title");
	window.location.href = ctx + "/user/" + search;
}

//jQuery就绪函数
$(function(){
	
	var ctx = $("#ctx").attr("title");

	//发布微博
	$("#publish_btn").click(function(){
		var content = $("textarea.weibo").val();
		var picture = $("img.upload").attr("id");
		ajaxpublish(content, -1, picture);
	});
	
	//发布表情
	$("#emotion_btn").click(function(){
		$("#emotion_layer").toggle();
	});
	
	//发布图片
	$("#picture_btn").click(function(){
		$("#picture_layer").toggle();
		$("#picture_upload").toggle();
	});
	
	$("#search_btn").click(function(){
		var search = $(".search_input").val();
		window.location.href = ctx + "/s/" + search;
	});
	
//	$("#uploadify").uploadify({
//        'uploader'       : ctx+'/swf/uploadify.swf',
//        'script'         : ctx+'/upload',
//        'cancelImg'      : ctx+'/images/cancel.png',
//        'folder'         : 'uploads',
//        'queueID'        : 'fileQuebue',
//        'auto'           : false,
//        'multi'          : false,
//		'fileExt': '*.jpg;*.gif;*.png',
//		'fileDesc': 'Image Files (.JPG, .GIF, .PNG)',
//        'simUploadLimit' : 2,
//		'removeCompleted': true,
//        'buttonText'     : escape('单张图片'),         
////        'onAllComplete': function (e, data) {
////        },
//        'onComplete'     : function(event, queueId, fileObj, response, data){
//			var jsondata =jQuery.parseJSON(response);
//			$("textarea.weibo").val('分享图片 ');
//			$("p.rawname").html(jsondata.rawname);
//			$("img.upload").attr("src", ctx+"/uploads/"+jsondata.newname);
//			$("img.upload").attr("id", jsondata.newname);
//			$("img.upload").attr("title", jsondata.rawname);
//			$("#picture_upload").hide();
//			$("#picture_display").show();
//    	}  
//    });
	
	
	
});